package com.wwwarehouse.resource_center.fragment.createobject.modifydelete;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.resource_center.R;
import com.wwwarehouse.resource_center.bean.goods.ModifyDeleteBean;
import com.wwwarehouse.resource_center.constant.ResourceConstant;
import com.wwwarehouse.resource_center.eventbus_event.GoodsEvent;
import com.wwwarehouse.resource_center.fragment.rules.TheParentFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * @author Joseph on 2017/10/20.
 *         <p/>
 *         物和资源修改删除搜索排序
 */

public class GoodsAndResModifyDeleteListFragment extends TheParentFragment {

    ListView lvlist;
    List<ModifyDeleteBean.ListBean> list;
    InfomationListAdaper listAdaper ;
    int num = 7;    //每一页的个数
    int pos;        //当前页数
    int count;      //总共几页
    int mItemHeight; //每一个条目的高度
    String type ;
    public static final int PAGINATION_ITEMORRESOURCE = 2;  //
    public static final int DELETE_ITEM_AND_RELATION = 3;  //
    String ownerUkid ;
    boolean isDelete; //修改还是删除
    String  mDeleteURl;
    String  mUrl;
    String mSeachContent ;
    String mSort ;
    private PopupWindow popupWindow;

    @Override
    protected int getContentId() {
        return R.layout.fragment_infomation_list;
    }

    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        return null;
    }

    @Override
    protected void init(View view) {
        lvlist = findView(view, R.id.lv_list);
    }

    @Override
    protected void loadDatas() {
        EventBus.getDefault().register(this);
        list = new ArrayList<>();
        try {
            Bundle b = getArguments();
            pos = b.getInt("pos");
            num = b.getInt("num");
            type = b.getString("type");
            ownerUkid = b.getString("ownerUkid");
            mSeachContent = b.getString("search");
            mSort = b.getString("sort");
            isDelete = b.getBoolean("isDelete");
            mUrl = b.getString("URL");
            count = b.getInt("count");
        } catch (Exception e) {
            e.printStackTrace();
        }
//        mActivity.setTitle(type.equals("1")?getString(R.string.infomation_create_item):getString(R.string.infomation_create_resources));
        reques(mSeachContent,mSort);
    }

    private void reques(String mSeachContent, String mSort) {
        Map map = new HashMap();
        Map<String, Object> query = new HashMap<>();
//        map.put("businessId", sp.getValue("businessId"));     //新接口文档没有
//        map.put("itemType", itemType);//按分类查询物或资源，非必须
//        map.put("currentStatus","");  //上下架（非必须）
        map.put("name", mSeachContent);                 //按名称模糊查询，非必须
        if (!TextUtils.isEmpty(type)){   //查询物
            map.put("type", type);

        }
        map.put("ownerUkid",ownerUkid);
        map.put("page", pos);
        map.put("size", num);
        map.put("sort", mSort);
//        map.put("query", query);
        httpPost(mUrl, map, PAGINATION_ITEMORRESOURCE, false, "");
    }

    @Override
    public void setTitle() {

    }

    private class InfomationListAdaper extends BaseAdapter {

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHodler viewHodler;
            if (convertView == null) {
                viewHodler = new ViewHodler();
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.adapter_goods_infomation, parent, false);
                ViewTreeObserver vto = lvlist.getViewTreeObserver();
                final View finalConvertView = convertView;
                vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        lvlist.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        LogUtils.showInfoLog("num:"+num);
                        ViewGroup.LayoutParams layoutParams = finalConvertView.getLayoutParams();
                        mItemHeight = lvlist.getHeight() / num;
                        layoutParams.height = mItemHeight;
                        LogUtils.showInfoLog("mItemHeight:"+mItemHeight);
                        finalConvertView.setLayoutParams(layoutParams);
                        LogUtils.showInfoLog("getHeight:"+lvlist.getHeight()+"mItemHeight:"+mItemHeight);
                    }
                });
                viewHodler.mName = (TextView) convertView.findViewById(R.id.goods_name);
                viewHodler.typeName = (TextView) convertView.findViewById(R.id.goods_category);
                viewHodler.aLineName = (TextView) convertView.findViewById(R.id.a_line_goods_name);
                viewHodler.aLine = (LinearLayout) convertView.findViewById(R.id.a_line);
                viewHodler.twoLine = (LinearLayout) convertView.findViewById(R.id.two_line);
                viewHodler.mImg = (ImageView) convertView.findViewById(R.id.img);
                convertView.setTag(viewHodler);
            } else {
                viewHodler = (ViewHodler) convertView.getTag();
            }
//            String typeCode = list.get(position).getType();
            switch (type){
                case "H_SHOP" :
                case "H_STOCK":
                    viewHodler.twoLine.setVisibility(View.VISIBLE);
                    viewHodler.aLine.setVisibility(View.GONE);
                    viewHodler.mName.setText(list.get(position).getName());
                    if (list.get(position).getCmAddress()!=null){
                        viewHodler.typeName.setText(list.get(position).getCmAddress().getAddress());
                    }
                    break;
                case "H_GOODS" :
                case "H_TOOLS"  :
                    viewHodler.aLineName.setText(list.get(position).getName());
                    break;
                case "H_STORE" :
                case "H_SALE"  :
                case "H_LABOUR":
                case "H_PROCESS" :
                case "H_SELL"  :
                case "H_TRANSPORT" :
                case "":
                    viewHodler.aLineName.setText(list.get(position).getDefinedName());
                    break;
                default  :
                    viewHodler.aLineName.setText(list.get(position).getDefinedName());
                    break;
            }
            if (TextUtils.isEmpty(list.get(position).getThumbnail())){
                viewHodler.mImg.setBackgroundResource(R.drawable.picture_no);
            }else {
                ImageLoader.getInstance().displayImage(list.get(position).getThumbnail(), viewHodler.mImg, new ImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String s, View view) {

                    }

                    @Override
                    public void onLoadingFailed(String s, View view, FailReason failReason) {
                        viewHodler.mImg.setBackgroundResource(R.drawable.picture_no);
                    }

                    @Override
                    public void onLoadingComplete(String s, View view, Bitmap bitmap) {

                    }

                    @Override
                    public void onLoadingCancelled(String s, View view) {

                    }
                });
            }
            if (!isDelete){ //  修改
                convertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        /**
                         * 物的分类：H_GOODS(商品)、H_TOOL(工具)、H_SHOP(店铺)、H_STOCK(仓库)、
                         * 资源的分类：H_SALE(供货)、H_STORE(仓储)、H_LABOUR(劳务)、H_PROCESS(加工)、H_SELL(销售)、H_TRANSPORT(运输)
                         */
//                        String typeCode = list.get(position).getTypeCode();
                        Fragment  fragment = null;
                        switch (type){
                            case "H_GOODS" :
                                fragment = new ModifyGoodsFragment();
                                break;
                            case "H_TOOLS" :
                                fragment = new ModifyToolsFragment();
                                break;
                            case "H_SHOP" :
                                fragment = new ModifyShopFragment();
                                break;
                            case "H_STOCK" :
                                fragment = new ModifyStockFragment();
                                break;
                            case "H_SALE" :
                            case "H_STORE" :
                            case "H_LABOUR" :
                            case "H_PROCESS" :
                            case "H_SELL" :
                            case "H_TRANSPORT" :
                                fragment = new ModifyResourcesFragment();
                                break;
                            default:
                                fragment = new ModifyResourcesFragment();
                                break;
                        }
                        //重置Title状态
                        ((BaseCardDeskActivity) mActivity).hideSearchInput();
                        ((BaseCardDeskActivity)mActivity).hideSearchTitle();
                        isShow = true ;
                        Bundle  bundle = new Bundle() ;
                        bundle.putParcelable("data",list.get(position));
                        bundle.putString("type",type);
                        bundle.putInt("pos",pos);
                        bundle.putString("ownerUkid",list.get(position).getOwnerUkid());
//                    bundle.putInt("pos", pos);       //当前第几页
//                    bundle.putInt("count", count);   //总页数
//                    bundle.putInt("num", num);       //每一页个数
//                    bundle.putInt("num", num);       //当前页数的第几条数据
                        fragment.setArguments(bundle);
                        pushFragment(fragment);
                    }
                });
            }else {
                convertView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        shwoPopupWindow(v, position);
                        return true;
                    }
                });
            }
            return convertView;
        }
        private void shwoPopupWindow(View view, final int position) {
            int[] location = new int[2];
            view.getLocationInWindow(location);
            View popupView = View.inflate(mActivity, R.layout.set_rule_modifyu_item_popupwindow_layout, null);
            popupWindow = new PopupWindow(popupView, view.getWidth(), view.getHeight() - 20);
            Drawable drawable = new ColorDrawable(Color.TRANSPARENT);
            LinearLayout mDeleteLayout = (LinearLayout) popupView.findViewById(R.id.delete_layout);

            mDeleteLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                    Map map = new HashMap();
                    map.put("ownerId",ownerUkid);
                    if (TextUtils.isEmpty(type)){
                        //资源
                        mDeleteURl = ResourceConstant.DELETE_RELATION;
                        map.put("rsDefinedUkid",list.get(position).getDefinedUkid());
                    }else {
                        //物
                        mDeleteURl = ResourceConstant.DELETE_ITEM;
                        map.put("abstractObjectUkid",list.get(position).getAbstractObjectUkid());
                    }
                    httpPost(mDeleteURl,map,DELETE_ITEM_AND_RELATION,true,"删除中…");
                }
            });
            popupWindow.setBackgroundDrawable(drawable);
            popupWindow.setOutsideTouchable(true);
            int x = location[0];
            int y = location[1];
            popupWindow.showAtLocation(view, Gravity.LEFT | Gravity.TOP, x, y);
        }
        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }
    }

    class ViewHodler {
        TextView mName;
        TextView typeName;
        ImageView mImg;
        TextView aLineName;
        LinearLayout twoLine ;
        LinearLayout aLine ;
    }
    public void onEventMainThread(GoodsEvent event) {
        switch (event.getCode()) {
            case GoodsEvent.GOODS_MODIFY:
                int pos = (int) event.getData();
                if (this.pos==pos){
                    reques(mSeachContent, mSort);
                }
                break;
        }
    }
    @Override
    public void onSuccess(CommonClass commonClass, int what) {
        switch (what){
            case PAGINATION_ITEMORRESOURCE:
                if (TextUtils.equals("0", commonClass.getCode())) {
                    ModifyDeleteBean goodsSelectLabelBean = JSON.parseObject(commonClass.getData().toString(), ModifyDeleteBean.class);
                    list = goodsSelectLabelBean.getList();
                    listAdaper = new InfomationListAdaper();
                    lvlist.setAdapter(listAdaper);
                }
                break;
            case DELETE_ITEM_AND_RELATION:
                if (TextUtils.equals("0", commonClass.getCode())) {
                    //删除成功
                    EventBus.getDefault().post(new GoodsEvent(GoodsEvent.GOODS_DELETE));
                }else {
                    toast(commonClass.getMsg());
                }
                break;
        }

    }

    @Override
    public void onReLoad(int code) {
        reques(mSeachContent, mSort);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (null!=popupWindow){
            popupWindow.dismiss();
        }
    }
}
